import logging
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from sdk.metadata.animation_meta import Text_intro, Text_outro

logger = logging.getLogger('api')


@api_view(['GET'])
@permission_classes([AllowAny])
def get_text_animations(request):
    """
    获取文本动画枚举列表
    
    返回:
    - intro_animations: 入场动画列表
    - outro_animations: 出场动画列表
    - loop_animations: 循环动画列表（固定列表）
    """
    try:
        # 获取入场动画
        intro_animations = []
        for animation in Text_intro:
            animation_info = {
                'name': animation.name,
                'display_name': animation.value.title if hasattr(animation.value, 'title') else animation.name,
                'is_vip': animation.value.is_vip if hasattr(animation.value, 'is_vip') else False,
                'duration': animation.value.duration if hasattr(animation.value, 'duration') else 0.5,
                'description': f"{'付费' if (hasattr(animation.value, 'is_vip') and animation.value.is_vip) else '免费'} - {animation.name}"
            }
            intro_animations.append(animation_info)

        # 获取出场动画
        outro_animations = []
        for animation in Text_outro:
            animation_info = {
                'name': animation.name,
                'display_name': animation.value.title if hasattr(animation.value, 'title') else animation.name,
                'is_vip': animation.value.is_vip if hasattr(animation.value, 'is_vip') else False,
                'duration': animation.value.duration if hasattr(animation.value, 'duration') else 0.5,
                'description': f"{'付费' if (hasattr(animation.value, 'is_vip') and animation.value.is_vip) else '免费'} - {animation.name}"
            }
            outro_animations.append(animation_info)

        # 循环动画（固定列表，因为没有专门的枚举）
        loop_animations = [
            {'name': '跳动', 'display_name': '跳动', 'is_vip': False, 'description': '免费 - 上下跳动效果'},
            {'name': '旋转', 'display_name': '旋转', 'is_vip': False, 'description': '免费 - 连续旋转效果'},
            {'name': '颤抖', 'display_name': '颤抖', 'is_vip': False, 'description': '免费 - 轻微颤抖效果'},
            {'name': '闪烁', 'display_name': '闪烁', 'is_vip': False, 'description': '免费 - 透明度闪烁效果'},
            {'name': '摇摆', 'display_name': '摇摆', 'is_vip': False, 'description': '免费 - 左右摇摆效果'},
            {'name': '波浪', 'display_name': '波浪', 'is_vip': False, 'description': '免费 - 波浪运动效果'},
            {'name': '环绕', 'display_name': '环绕', 'is_vip': False, 'description': '免费 - 圆形环绕效果'},
            {'name': '钟摆', 'display_name': '钟摆', 'is_vip': False, 'description': '免费 - 钟摆摆动效果'},
            {'name': '翻转', 'display_name': '翻转', 'is_vip': False, 'description': '免费 - 水平翻转效果'},
            {'name': '雨刷', 'display_name': '雨刷', 'is_vip': False, 'description': '免费 - 雨刷摆动效果'},
        ]

        # 按照免费/付费分组排序
        intro_animations.sort(key=lambda x: (x['is_vip'], x['name']))
        outro_animations.sort(key=lambda x: (x['is_vip'], x['name']))

        logger.info(f"✅ 成功获取动画枚举: 入场{len(intro_animations)}个，出场{len(outro_animations)}个，循环{len(loop_animations)}个")

        return Response({
            'success': True,
            'message': '动画枚举获取成功',
            'data': {
                'intro_animations': intro_animations,
                'outro_animations': outro_animations,
                'loop_animations': loop_animations,
                'stats': {
                    'intro_total': len(intro_animations),
                    'intro_free': len([a for a in intro_animations if not a['is_vip']]),
                    'intro_vip': len([a for a in intro_animations if a['is_vip']]),
                    'outro_total': len(outro_animations),
                    'outro_free': len([a for a in outro_animations if not a['is_vip']]),
                    'outro_vip': len([a for a in outro_animations if a['is_vip']]),
                    'loop_total': len(loop_animations),
                }
            }
        })

    except Exception as e:
        logger.error(f"❌ 获取动画枚举失败: {str(e)}")
        return Response({
            'success': False,
            'message': f'获取动画枚举失败: {str(e)}'
        }, status=500)


@api_view(['GET'])
@permission_classes([AllowAny])
def get_animation_categories(request):
    """
    获取动画分类信息
    
    返回:
    - categories: 动画分类统计
    """
    try:
        # 统计入场动画分类
        intro_free = []
        intro_vip = []
        
        for animation in Text_intro:
            is_vip = animation.value.is_vip if hasattr(animation.value, 'is_vip') else False
            animation_info = {
                'name': animation.name,
                'display_name': animation.value.title if hasattr(animation.value, 'title') else animation.name
            }
            
            if is_vip:
                intro_vip.append(animation_info)
            else:
                intro_free.append(animation_info)

        # 统计出场动画分类
        outro_free = []
        outro_vip = []
        
        for animation in Text_outro:
            is_vip = animation.value.is_vip if hasattr(animation.value, 'is_vip') else False
            animation_info = {
                'name': animation.name,
                'display_name': animation.value.title if hasattr(animation.value, 'title') else animation.name
            }
            
            if is_vip:
                outro_vip.append(animation_info)
            else:
                outro_free.append(animation_info)

        return Response({
            'success': True,
            'message': '动画分类获取成功',
            'data': {
                'intro': {
                    'free': intro_free,
                    'vip': intro_vip,
                    'free_count': len(intro_free),
                    'vip_count': len(intro_vip)
                },
                'outro': {
                    'free': outro_free,
                    'vip': outro_vip,
                    'free_count': len(outro_free),
                    'vip_count': len(outro_vip)
                },
                'summary': {
                    'total_animations': len(list(Text_intro)) + len(list(Text_outro)),
                    'total_free': len(intro_free) + len(outro_free),
                    'total_vip': len(intro_vip) + len(outro_vip)
                }
            }
        })

    except Exception as e:
        logger.error(f"❌ 获取动画分类失败: {str(e)}")
        return Response({
            'success': False,
            'message': f'获取动画分类失败: {str(e)}'
        }, status=500)
